﻿(function () {
    var id = arg0;
    if (!id) id = 0;
    var Template = {
        TemplateId: id,
        Title: "",
        Form: "",
        GraphJson: "",
        TypeId: 0,
        Params: []
    };
    //公用变量
    //var PublicParams = [{ name: "岗位", value: X_POSTS }];
    var graph;
    LoadTemplate("/WF", "流程设计", "Templates_Add.aspx?TemplateId=" + id, 1100, 650, function load($dialog) {
        $("select[name=TypeId]", "#WF-Templates_Add").addOption("选择分类", "");
        $.map(WF_TypesArray, function (item) {
            $("select[name=TypeId]", "#WF-Templates_Add").addOption(item.Name, item.TypeId);
        });
        if (id > 0) {
            $.ajax({
                type: "get",
                url: "/WF/Services/WF_Templates.asmx/Query",
                dataType: 'json',
                data: { id: id },
                contentType: "application/json;utf-8",
                success: function (data) {
                    Template.GraphJson = data.d.GraphJson;
                    Template.Form = data.d.Form;
                    Template.Title = data.d.Title;
                    Template.TypeId = data.d.TypeId;
                    $("select[name=TypeId]", "#WF-Templates_Add").val(Template.TypeId);
                    $("input[name=title]", "#WF-Templates_Add").val(Template.Title);
                }, async: false
            });
        }
        //graph代码
        var property = {
            width: 870,
            height: 475,
            toolBtns: ["start round", "end", "task", "node", "chat", "state", "plug", "join", "fork", "complex mix"],
            haveHead: true,
            headBtns: ["undo", "redo"],//如果haveHead=true，则定义HEAD区的按钮
            haveTool: true,
            haveGroup: true,
            useOperStack: true,
            initLabelText: '流程设计'
        };
        var remark = {
            cursor: "选择指针",
            direct: "转换连线",
            start: "开始结点",
            "end": "结束结点",
            "task": "任务结点",
            node: "自动结点",
            chat: "决策结点",
            state: "状态结点",
            plug: "附加插件",
            fork: "分支结点",
            "join": "联合结点",
            "complex": "复合结点",
            group: "组织划分框编辑开关"
        };
        graph = $.createGooFlow($("#graph"), property);
        graph.setNodeRemarks(remark);

        if (Template.GraphJson) {
            var _jsonData = $.parseJSON(Template.GraphJson);
            var initNum = 0;
            $.map(_jsonData.nodes, function (k, item) {
                var _val = parseInt(item.replace("graph_node_", ""));
                if (initNum < _val) initNum = _val;
            });
            $.map(_jsonData.lines, function (k, item) {
                var _val = parseInt(item.replace("graph_line_", ""));
                if (initNum < _val) initNum = _val;
            });
            _jsonData.initNum = initNum;
            graph.loadData(_jsonData);
        }
        //if (Template.GraphJson) graph.loadData($.parseJSON(Template.GraphJson));
        graph.onItemFocus = function (id, type) {
            //加载属性
            $("#Property").empty();
            switch (type) {
                case "line":
                    var line = graph.$lineData[id];
                    //取其父节点
                    var from = graph.$nodeData[line.from];
                    var to = graph.$nodeData[line.to];

                    var str = "<table class='' style='width:180px'>";
                    str += "<tr><th style='width:60px'>线条名称</th><th>{0}</th></tr>".format(line.name);
                    str += "<tr><td>起止</td><td>{0}-{1}</td>".format(from.name, to.name);
                    var paramsArray = ["岗位", "角色", "部门", "权限"];
                    var operArray = [{ text: "等于", value: "==" },
                        { text: "不等于", value: "!=" },
                        { text: "大于", value: ">" },
                        { text: "小于", value: "<" },
                        { text: "大于等于", value: ">=" },
                        { text: "小于等于", value: "<=" },
                        { text: "包含", value: "like" },
                        { text: "不包含", value: "not like" }];
                    if (from.type == "fork") {
                        str += "<tr><td>变量</td>";
                        str += "<td><select name='ConditionParam'><option value=''>选择变量</option>";
                        renderFormUI();//刷新form
                        ///从Form里提取变量
                        Template.Params = [];
                        $("#divFormDesignerVisual").find("input").each(function () {
                            Template.Params.push({
                                name: $(this).attr("name"),
                                validate: $(this).attr("validate")
                            });
                        });
                        for (var i = 0; i < Template.Params.length; i++) {
                            str += "<option value='{0}'>{1}</option>".format(Template.Params[i].name, Template.Params[i].name);
                        }

                        str += "</select></td></tr>";
                        str += "<tr><td>条件</td>";
                        str += "<td><select name='ConditionOper'>";
                        for (var i = 0; i < operArray.length; i++) {
                            str += "<option value='{0}' {2}>{1}</option>".format(operArray[i].value, operArray[i].text, (i == 0 ? "selected" : ""));
                        }
                        str += "</select></td></tr>";
                        str += "<tr><td>值</td><td><input type='text' class='width-short' name='ConditionValue' /></td></tr>";
                    }

                    str += "</table>";

                    $("#Property").append(str);
                    if (from.type == "fork") {
                        var commons = ["USERID", "POSTID", "POSTNAME", "USERNAME", "COPID", "COPNAME", "DEPARTNAME", "DEPARTID", "SEX", "ENTRYTIME", "GROUPNO", "STRENGTH"];
                        for (var i = 0; i < commons.length; i++) {
                            $("select[name=ConditionParam]").addOption(commons[i], commons[i]);
                        }
                    }
                    //赋值
                    $("select", "#WF-Templates_Add").each(function (k, v) {
                        if (line[$(v).attr("name")]) {
                            $(v).val(line[$(v).attr("name")]);
                        }
                    });
                    $("input", "#WF-Templates_Add").each(function (k, v) {
                        if (line[$(v).attr("name")]) {
                            $(v).val(line[$(v).attr("name")]);
                        }
                    });
                    //事件
                    $("select", "#WF-Templates_Add").change(function () {
                        line[$(this).attr("name")] = $(this).val();
                    });
                    $("input", "#WF-Templates_Add").change(function () {
                        line[$(this).attr("name")] = $(this).val();
                    });
                    break;
                case "node":
                    var node = graph.$nodeData[id];
                    console.log(node);
                    if (!node.NodeSpecifyType) { node.NodeSpecifyType = ""; }
                    if (!node.NodeSpecifyValue) { node.NodeSpecifyValue = ""; }
                    var str = "<table class='' style='width:180px'>";
                    str += "<tr><th style='width:60px'>节点名称</th><th>{0}</th></tr>".format(node.name);
                    switch (node.type) {
                        case "start round":
                            //开始节点
                            $("#Property").append("</table>" + str);
                            break;
                        case "fork":
                            //开始节点
                            $("#Property").append("</table>" + str);
                            break;
                        case "end"://结束
                            //开始节点
                            $("#Property").append("</table>" + str);
                            break;
                        default://决策节点

                            str += "<tr><td>到达执行sql</td><td><textarea name='NodeBeforeSql' style='width:110px;height:80px' /></td>";
                            str += "<tr><td>完成执行sql</td><td><textarea name='NodePassSql' style='width:110px;height:80px' /></td>";
                            str += "<tr><td>完成执行js</td><td><textarea name='NodePassJs' style='width:110px;height:80px' /></td>";
                            str += "<tr><td>驳回执行sql</td><td><textarea name='NodeBackSql' style='width:110px;height:80px' /></td>";
                            str += "<tr><td>审批模板</td><td><textarea name='SpecifyTemplate' style='width:110px;height:80px' /></td>";
                            str += addProperty("用户类型");
                            str += addProperty("录入值");
                            $("#Property").append("</table>" + str);
                            break;
                    }
                    //赋值
        
                    $("select", "#WF-Templates_Add").each(function (k, v) {
                        if (node[$(v).attr("name")]) {
                            var _val = node[$(v).attr("name")];
                            $(v).attr("value1", _val).attr("value", _val).val(_val);
                        }
                    });
                    $("input", "#WF-Templates_Add").each(function (k, v) {
                        if (node[$(v).attr("name")]) {
                            $(v).val(node[$(v).attr("name")]);
                        }
                    });
                    $("textarea", "#WF-Templates_Add").each(function (k, v) {
                        if (node[$(v).attr("name")]) {
                            $(v).val(node[$(v).attr("name")]);
                        }
                    });
                    //事件
                    $("select", "#WF-Templates_Add").change(function () {
                        node[$(this).attr("name")] = $(this).val();
                    });
                    $("input", "#WF-Templates_Add").change(function () {
                        node[$(this).attr("name")] = $(this).val();
                    });
                    $("textarea", "#WF-Templates_Add").change(function () {
                        node[$(this).attr("name")] = $(this).val();
                    });

                    //事件
                    $("select[name=NodeSpecifyType]").change(function () {
                        switch ($(this).val()) {
                            case "0"://用户
                                $("select[name=NodeSpecifyTypeValue]").xBindData({
                                    "url": "/RBAC/Services/RBAC_Users.asmx/GetLists", "text": "UserName", "value": "UserId",
                                    data: { rows: 35535, injob: 1, idAndName: 1,page:1 }
                                });
                                break;
                            case "1"://部门
                                $("select[name=NodeSpecifyTypeValue]").xBindData({
                                    "url": "/Org/Services/Org_Departs.asmx/GetLists", "text": "DepartName", "value": "DepartId",
                                    data: { rows: 35535, injob: 1, idAndName: 1 }
                                });
                                break;
                            case "2"://岗位
                                $("select[name=NodeSpecifyTypeValue]").xBindData({
                                    "url": "/Org/Services/Org_Posts.asmx/GetLists", "text": "PostName", "value": "PostId",
                                    data: { rows: 35535, injob: 1, idAndName: 1 }
                                });
                                break;
                            case "3"://角色
                                $("select[name=NodeSpecifyTypeValue]").xBindData({
                                    "url": "/RBAC/Services/RBAC_Roles.asmx/GetLists", "text": "RoleName", "value": "RoleId",
                                    data: { rows: 35535, injob: 1, UserId: 0 }
                                });
                                break;
                                //case "4"://权限
                                //    $("select[name=NodeSpecifyTypeValue]").xBindData({
                                //        "url": "/Org/Services/S_Org_Departs.asmx/GetLists", "text": "title", "value": "id",
                                //        data: { rows: 35535, injob: 1, idAndName: 1, ParentId: $COPID }
                                //    });
                                //    break;
                        }
                    });
                    $("select[name=NodeSpecifyType]").change();

                    break;
            }
            return true;
        };
        var properties = [
            {
                name: "用户类型", value: "<select name='NodeSpecifyType'>" +
                                  "<option value='0'>指定用户</option>" +
                                  "<option value='1'>指定部门</option>" +
                                  "<option value='2'>指定岗位</option>" +
                                  "<option value='3'>指定角色</option>" +
                                  //"<option value='4'>指定权限</option>" +
                                  "</select>"
            }, {
                name: "录入值", value: "<select type='text' name='NodeSpecifyTypeValue' style='width:90px'><option>选择</option></select>"
            }
        ];
        function addProperty(name) {
            for (var j = 0; j < properties.length; j++) {
                if (properties[j].name == name) {
                    return "<tr><td>" + properties[j].name + "</td><td>" + properties[j].value + "</td></tr>";
                }
            }
        }

        //form代码
        $('#tabFormDesigner').tabs({
            border: false,
            onSelect: function (title) {
                if (title == "可视化") {
                    renderFormUI();
                }
                else if (title == "源码") {
                    getSource();
                }
            }
        });
        ///form设计，Form源码渲染Div
        function renderFormUI() {
            var content = $("textarea[name=txtFormDesignerCodeSource]", "#WF-Templates_Add").val();
            $("#divFormDesignerVisual").html(content);
            return content;
        }
        ///Form设计，取得Form源码
        function getSource() {
            $("textarea[name=txtFormDesignerCodeSource]", "#WF-Templates_Add").val($("#divFormDesignerVisual").formhtml());
        }
        $("textarea[name=txtFormDesignerCodeSource]", "#WF-Templates_Add").val(Template.Form);
        $dialog.dialog({
            buttons: [
                {
                    text: '设计好了',
                    handler: function () {
                        ///有效性验证
                        var pass = true;
                        for (var s = 0; s < graph.$nodeData.length; s++) {
                            if ((!graph.$nodeData[s].NodeSpecifyType) ||
                                (!graph.$nodeData[s].NodeSpecifyValue)
                                ) {
                                pass = false;
                                break;
                            }
                        }
                        if (!pass) {
                            $.messager.show({ title: '操作提示', msg: "每个节点都要制定用户类型。" });
                            return;
                        }
                        //节点和线名称不能重复
                        var names = [];
                        for (var s in graph.$nodeData) {
                            var _name = graph.$nodeData[s].name;
                            if (names.indexOf(_name) > -1) {
                                pass = false;
                                break;
                            }
                            names.push(_name);
                        }
                        if (!pass) {
                            $.messager.show({ title: '操作提示', msg: "节点名称不能重复。" });
                            return;
                        }
                        names = [];
                        for (var s in graph.$lineData) {
                            var _line = graph.$lineData[s].name;
                            if (!_line) continue;
                            if (names.indexOf(_line) > -1) {
                                pass = false;
                                break;
                            }
                            names.push(_line);
                        }
                        if (!pass) {
                            $.messager.show({ title: '操作提示', msg: "连线名称不能重复！" });
                            return;
                        }

                        Template.Title = $("input[name=title]", "#WF-Templates_Add").val();
                        Template.TypeId = $("select[name=TypeId]", "#WF-Templates_Add").val();
                        if (!Template.Title) {
                            $.messager.show({ title: '操作提示', msg: "没有定义流程名称！" });
                            return;
                        }
                        if (!Template.TypeId) {
                            $.messager.show({ title: '操作提示', msg: "没有选择流程类型！" });
                            return;
                        }
                        var tabSelected = $('#tabFormDesigner').tabs('getSelected');
                        var tab = tabSelected.panel('options');
                        if (tab.title == "源码") {
                            Template.Form = renderFormUI();
                        } else {
                            Template.Form = encodeURIComponent($("#divFormDesignerVisual").formhtml());
                        }
                        Template.GraphJson = JSON.stringify({
                            nodes: graph.$nodeData,
                            lines: graph.$lineData
                        });

                        $.post("/WF/Services/WF_Templates.asmx/Add", Template, function (r) {
                            switch ($(r).find("ServiceStateKeys").text()) {
                                case "Success":
                                    $.messager.show({ title: '操作提示', msg: "操作成功。" });
                                    callPageRender('WF-Templates_List');
                                    $dialog.dialog("close");
                                    break;
                                case "TimeOut":
                                    break;
                                default:
                                    break;
                            }
                        });
                    }
                }, {
                    text: '取消',
                    handler: function () {
                        $dialog.dialog("close");
                    }
                }]
        });
    });
})();